package com.cy.jt.sercurity.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/*
* 默认的访问拒绝处理器,用于处理访问被拒绝的异常处理器对象
* Access 访问
* Denied 拒绝
*
* */
public class DefaultAccessDeniedExceptionHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       AccessDeniedException exception) throws IOException, ServletException {
        //加入访问被拒绝了向客户端响应一个JSON串
        //响应数据的编码
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        Map<String,Object> map = new HashMap<>();
        map.put("state",HttpServletResponse.SC_FORBIDDEN);
        map.put("message", "你没有访问权限,请联系管理员");
        String jsonStr = new ObjectMapper().writeValueAsString(map);
        out.println(jsonStr );
        out.flush();
    }
}
